import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bilibili/core/extension/int_extension.dart';
import 'package:flutter_bilibili/core/service/utils/json_parse.dart';
import 'package:flutter_bilibili/core/extension/color_extensions.dart';
import '../../../../core/model/big_data_model.dart';
import '../util_chart/indicator.dart';

class HYPieChartSamples extends StatefulWidget {
  const HYPieChartSamples({Key? key}) : super(key: key);

  @override
  State<HYPieChartSamples> createState() => _HYPieChartSamplesState();
}

class _HYPieChartSamplesState extends State<HYPieChartSamples> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Theme.of(context).canvasColor,
      child: ListView(
        children: [
          SizedBox(
            height: 8.px,
          ),
          const Padding(
            padding: EdgeInsets.only(
              left: 20,
              right: 20,
            ),
            child: BuildPieChartSampleSample01(),
          ),
        ],
      ),
    );
  }
}

class BuildPieChartSampleSample01 extends StatefulWidget {
  const BuildPieChartSampleSample01({Key? key}) : super(key: key);

  @override
  State<BuildPieChartSampleSample01> createState() =>
      _BuildPieChartSampleSample01State();
}

class _BuildPieChartSampleSample01State
    extends State<BuildPieChartSampleSample01> {
  List<ReduceType> reduceTypeList = [];
  int touchedIndex = -1;

  @override
  void initState() {
    super.initState();
    HYJsonParse.getBigData().then((value) {
      setState(() {
        reduceTypeList = value.reduceFollower.reduceType;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return reduceTypeList.isNotEmpty
        ? AspectRatio(
            aspectRatio: 1,
            child: Card(
              color: Colors.white,
              child: Column(
                children: [
                  const SizedBox(
                    height: 28,
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      Indicator(
                        color: const Color(0xff0293ee),
                        text: '生活',
                        isSquare: false,
                        size: touchedIndex == 0 ? 18 : 16,
                        textColor:
                            touchedIndex == 0 ? Colors.black : Colors.grey,
                      ),
                      Indicator(
                        color: const Color(0xfff8b250),
                        text: '游戏',
                        isSquare: false,
                        size: touchedIndex == 1 ? 18 : 16,
                        textColor:
                            touchedIndex == 1 ? Colors.black : Colors.grey,
                      ),
                      Indicator(
                        color: const Color(0xff845bef),
                        text: '娱乐',
                        isSquare: false,
                        size: touchedIndex == 2 ? 18 : 16,
                        textColor:
                            touchedIndex == 2 ? Colors.black : Colors.grey,
                      ),
                      Indicator(
                        color: const Color(0xff13d38e),
                        text: '动画',
                        isSquare: false,
                        size: touchedIndex == 3 ? 18 : 16,
                        textColor:
                            touchedIndex == 3 ? Colors.black : Colors.grey,
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 18,
                  ),
                  Expanded(
                    child: AspectRatio(
                      aspectRatio: 1,
                      child: PieChart(
                        PieChartData(
                            pieTouchData: PieTouchData(touchCallback:
                                (FlTouchEvent event, pieTouchResponse) {
                              setState(() {
                                if (!event.isInterestedForInteractions ||
                                    pieTouchResponse == null ||
                                    pieTouchResponse.touchedSection == null) {
                                  touchedIndex = -1;
                                  return;
                                }
                                touchedIndex = pieTouchResponse
                                    .touchedSection!.touchedSectionIndex;
                              });
                            }),
                            startDegreeOffset: 180,
                            borderData: FlBorderData(
                              show: false,
                            ),
                            sectionsSpace: 0,
                            centerSpaceRadius: 30,
                            sections: showingSections()),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          )
        : Container();
  }

  List<PieChartSectionData> showingSections() {
    return List.generate(
      reduceTypeList.length,
      (i) {
        final isTouched = i == touchedIndex;
        final opacity = isTouched ? 1.0 : 0.6;
        final fontSize = isTouched ? 20.0 : 16.0;
        final radius = isTouched ? 110.0 : 100.0;
        final widgetSize = isTouched ? 55.0 : 40.0;
        final svgList = [
          'assets/image/icon/pie_icon01.png',
          'assets/image/icon/pie_icon02.png',
          'assets/image/icon/pie_icon03.png',
          'assets/image/icon/pie_icon04.png',
        ];

        const List<Color> colors = [
          Color(0xff0293ee),
          Color(0xfff8b250),
          Color(0xff845bef),
          Color(0xff13d38e)
        ];

        return PieChartSectionData(
          showTitle: true,
          color: colors[i].withOpacity(opacity),
          value: double.parse(reduceTypeList[i].percent.substring(0, 5)),
          title: reduceTypeList[i].key,
          radius: radius,
          titleStyle: TextStyle(
              fontSize: fontSize,
              fontWeight: FontWeight.bold,
              color: Color(0xff044d7c)),
          titlePositionPercentageOffset: 0.55,
          borderSide: isTouched
              ? BorderSide(color: colors[i].darken(40), width: 6)
              : BorderSide(color: colors[i].withOpacity(0)),
          badgeWidget: i % 2 == 0
              ? _Badge(
                  svgList[i],
                  size: widgetSize,
                  borderColor: const Color(0xff13d38e),
                )
              : Container(),
        );
      },
    );
  }
}

class _Badge extends StatelessWidget {
  final String imageAsset;
  final double size;
  final Color borderColor;

  const _Badge(
    this.imageAsset, {
    Key? key,
    required this.size,
    required this.borderColor,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: PieChart.defaultDuration,
      width: size,
      height: size,
      decoration: BoxDecoration(
        color: Colors.white,
        shape: BoxShape.circle,
        border: Border.all(
          color: borderColor,
          width: 2,
        ),
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: Colors.black.withOpacity(.5),
            offset: const Offset(3, 3),
            blurRadius: 3,
          ),
        ],
      ),
      padding: EdgeInsets.all(size * .15),
      child: Center(
        child: Image.asset(
          imageAsset,
          fit: BoxFit.contain,
        ),
      ),
    );
  }
}
